package de.hhbk.feedbackmodul.daobeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.hhbk.feedbackmodul.daointerfaces.UserRoleDaoIF;
import de.hhbk.feedbackmodul.entities.UserRole;

@Stateless
public class UserRoleDaoBean implements UserRoleDaoIF {

	@PersistenceContext(unitName = "FeedbackModulEJB")
	private EntityManager manager;
	
	private Logger logger = Logger.getLogger(this.getClass());

	@SuppressWarnings("unchecked")
	@Override
	public List<UserRole> getAllUserRoles() throws Exception{
		try
		{
			Query query = manager.createQuery("SELECT ur FROM UserRole ur", UserRole.class);
			return (List<UserRole>)query.getResultList();
		}
		catch(Exception e)
		{
			logger.error("Error while reading UserRoles: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void createUserRole(UserRole userRole) throws Exception {
		try
		{
			manager.persist(userRole);
		}
		catch(Exception e)
		{
			logger.error("Error while persisting UserRole: "+e.getMessage(), e);
			throw e;
		}
		
	}

	@Override
	public void updateUserRole(UserRole userRole) throws Exception {
		try
		{
			manager.merge(userRole);
		}
		catch(Exception e)
		{
			logger.error("Error while updating UserRole: "+e.getMessage(), e);
			throw e;
		}
	}

	@Override
	public void deleteUserRole(UserRole userRole) throws Exception {
		try
		{
			UserRole userRoleToDelete = manager.find(UserRole.class, userRole.getId());
			manager.remove(userRoleToDelete);
		}
		catch(Exception e)
		{
			logger.error("Error while deleting UserRole: "+e.getMessage(), e);
			throw e;
		}
		
	}
	
}
